package com.jzit168.module_home.ui.home

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.jzit168.library_arouter.ARouterConstant
import com.jzit168.library_arouter.startARouter
import com.jzit168.library_base.baseVBVM.BaseVBVMFragment
import com.jzit168.library_base.ext.asLiveDataUI
import com.jzit168.library_base.ext.toast
import com.jzit168.library_utils.LogUtil
import com.jzit168.module_home.MyDividerItemDecoration
import com.jzit168.module_home.R
import com.jzit168.module_home.databinding.HomeFragmentBinding
import kotlinx.coroutines.flow.flow

@Route(path = ARouterConstant.Home.toHomeFragment)
class HomeFragment : BaseVBVMFragment<HomeFragmentBinding, HomeViewModel>() {

    private val contentAdapter by lazy { ContentAdapter() }

    private val headerAdapter by lazy { HeaderAdapter() }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): HomeFragmentBinding = HomeFragmentBinding.inflate(inflater, container, false)

    override fun getViewModel(): Class<HomeViewModel> = HomeViewModel::class.java

    override fun onView() {
        super.onView()
        initRecyclerview()
        viewModel.getData().asLiveDataUI(this, {
            contentAdapter.setList(it)
            headerAdapter.addData(R.drawable.ic_empty)
        })
    }

    private fun initRecyclerview() {
        val concatAdapter = ConcatAdapter(contentAdapter)
        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            addItemDecoration(
                MyDividerItemDecoration(
                    requireContext(),
                    MyDividerItemDecoration.HORIZONTAL
                ).also {
                    it.drawable =
                        ResourcesCompat.getDrawable(resources, R.drawable.drawable_item_line, null)
                }
            )
            adapter = concatAdapter
        }
        headerAdapter.setOnItemClickListener { _, _, position ->
            startARouter(ARouterConstant.Login.toLoginActivity)
        }
        contentAdapter.setOnItemClickListener { _, _, position ->
            when (position) {
                0 -> {
                    startARouter(ARouterConstant.Camera.toCameraActivity1)
                }
                else -> {
                    startARouter(ARouterConstant.Camera.toCameraActivity)
                }
            }
        }
    }
}